// pages/bangding/bangding.js
const app = getApp()
var interval = null //倒计时函数
Page({
  data: {
    btndisabled:false,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    date: '请选择日期',
    fun_id: 2,
    time: '获取验证码', //倒计时 
    currentTime: 61,
    errorMsg:"",
    canbind:false,
    bindclick:true
  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    }
    //打开此页必须获取到Openid，如果没有，再次请求
    if(app.globalData.openid==null||app.globalData.openid==""){
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          if (res.code) {
            var that = this;
            //发起网络请求
            wx.request({
              url: app.globalData.serverPath + "api/authenticate/wechat/" + res.code,
              method: 'GET',
              success: function (res) {
                console.log(res);
                if (res.data.errorCode > 0) {
                  //获取微信openid出错。
                  wx.showModal({
                    title: '错误提示',
                    content: '微信授权登录错误【' + res.data.errorCode + '】',
                    showCancel: false
                  })
                } else {
                  if (res.data.result == 0 && res.data.message == "微信用户身份未绑定。") {
                    if (res.data.data.openid) {
                      app.globalData.openid = res.data.data.openid;
                      that.setData({
                        canbind:true
                      });
                    } else {
                      wx.showModal({
                        title: '错误提示',
                        content: '获取微信授权身份错误',
                        showCancel: false
                      })
                    }
                    wx.hideLoading();
                  } 
                }
              }
            })
          } else {
            console.log('获取用户登录态失败！' + res.errMsg)
          }
        }
      })
    }else{
      this.setData({
        canbind: true
      });
    }
  },
  getCode: function (options) {
  //  console.log("aaaaa");
    var that = this;
    var currentTime = that.data.currentTime
    interval = setInterval(function () {
      currentTime--;
      that.setData({
        time: currentTime + '秒'
      })
      if (currentTime <= 0) {
        clearInterval(interval)
        that.setData({
          time: '重新发送',
          currentTime: 61,
          disabled: false
        })
      }
    }, 1000)
  },
  
  getVerificationCode:function() {
    var that = this;
    console.log(that.data.btndisabled);
    if (that.data.btndisabled){
      console.log("不可点击");
        return;
      }else{
        // if(!this.data.phone||this.data.phone==""){
        //   wx.showModal({
        //     title: '错误提示',
        //     content: '请输入手机号码',
        //     showCancel:false
        //   })
        //   return;
        // }
        wx.showLoading({
          title: '获取验证码'
        });


        wx.request({
          method: 'POST',
          url: app.globalData.serverPath + "api/send-sms?mobile="+this.data.phone,
          header: {
            'Authorization': app.globalData.token
          },
          success:function(res){

          },
          complete:function(){
            wx.hideLoading();
          }
        })

        that.setData({btndisabled:true});
        that.getCode();        
        setTimeout(function(){
          that.data.btndisabled=false;
        },60*1000)
      }
  },

  /**点击绑定之前的验证 */
  validatePost:function(account,phone,phonecode){
    this.setData({errorMsg: "" });
    if (!account || account == "") {
      wx.showModal({
        title: '错误提示',
        content: "请输入需绑定的平台账号。",
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false;
    }
    if(!phone || phone==""){
      wx.showModal({
        title: '错误提示',
        content: "请输入正确的手机号码。",
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false;
    }
    if (!phonecode || phonecode == ""){
      wx.showModal({
        title: '错误提示',
        content: "请输入正确的验证码。",
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            //console.log('用户点击确定')
          } else if (res.cancel) {
            //console.log('用户点击取消')
          }
        }
      })
      return false;
    }
    if (!app.globalData.openid || app.globalData.openid==""){
      wx.showModal({
        title: '错误提示',
        content: "获取微信授权身份错误",
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            //console.log('用户点击确定')
          } else if (res.cancel) {
            //console.log('用户点击取消')
          }
        }
      })
      return false;
    }

    return true;
  },
  phoneblur:function(e){
    this.setData({
      phone: e.detail.value
    });
  },

  formSubmit: function(e){
    var that=this;
    if(!this.data.bindclick) return;
    this.setData({bindclick:false});
    console.log('form发生了submit事件，携带数据为：', e.detail.value);
    var formvalue = e.detail.value;
    if(this.validatePost(formvalue.account,formvalue.phone,formvalue.phonecode)){
      wx.showLoading({
        title: '登录中...'
      })
      //表单请求
      wx.request({
        url: app.globalData.serverPath + "api/authenticate/wechat/bind",
        header:{
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          account:formvalue.account,
          openid:app.globalData.openid,
          phone: formvalue.phone,
          randomcode: formvalue.phonecode
        },
        method:'POST',
        success: function (res) {
          console.log(res);
          if (res.statusCode!=200){
            wx.showModal({
              title: res.data.title ? res.data.title:'错误提示',
              content: res.data.message ? res.data.message : res.data.errormsg,
              showCancel:false
            })
            that.setData({ bindclick: true });
            return;
          }
          if(res.data.id>0){
            app.initApp(function(){
              app.processLogin(app.globalData.loginresult,function(){
                wx.hideLoading();
                wx.reLaunch({
                  url: '../main-driver/main-driver'
                });
              });
              that.setData({ bindclick: true });
            });
          }
          
        },
        fail:function (err) {
          that.setData({ bindclick: true });
        }
      });
    }
  }

})